﻿using FreesenseSubAIS.Core;
using FreesenseSubAIS.ImageProcess;
using FreesenseSubAIS.InspProcess;
using FreesenseSubAIS.UI;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.UI;

namespace FreesenseSubAIS
{
    public partial class FormMain : RadForm
    {
        private string _productversion;
        const string Wraninfo = "启用相机请在参数设置界面-算法参数-相机管理-启用相机";
        public static bool MainInspEnable = false;
        private readonly ILogger _log;
        Bitmap[] btlist = new Bitmap[3];
        private int tempexprosetime;
        private string Msg;
        private AutoResetEvent _retset;
        private AutoResetEvent _resetEvent;//单次批量检测完成
        public FormMain()
        {
            InitializeComponent();
            listView1.MultiSelect = false;
            listView1.LargeImageList = new ImageList();
            listView1.LargeImageList.ImageSize = new Size(100, 100);
            InitApplication();
            _productversion = ProductVersion;
            _log = LogManager.GetCurrentClassLogger();
            _retset = new AutoResetEvent(true);
            _resetEvent = new AutoResetEvent(false);
            Device.Init();
        }
        private void FormMain_Shown(object sender, EventArgs e)
        {
            try
            {
                _log.Info(string.Format("进入API从机检测系统，版本号{0}", this.ProductVersion));
                autoAddIDRCB.Checked = Device.SaveSourceImage;
                this.Enabled = false;
                Task actionMain0 = Task.Run(() =>
                {
                    ImageManage.Instance.InitCamera(Device.Parameter.CameraList[0]);
                    ImageManage.Instance.RefrushListView += c00_RefrushListView;//更新主界面小图显示
                    if (ImageManage.Instance.ConnectState)
                    {
                        ImageManage.Instance.RefrushContinueCapturePic += c00_RefrushContinueCapturePic;
                        cameraID_tx.BackColor = Color.Lime;
                    }
                    else
                    {
                        cameraID_tx.BackColor = Color.Yellow;
                    }
                });
                InspEntity.Intance.GetProjectConfig();
                InspEntity.Intance.MsgEvent += Intance_MsgEvent;
                InspEntity.Intance.ChangValue += ProgressValueChanged;
                Device.IsHostDisPlay = HostDis.Checked;
                cameraID_tx.Text = Device.Parameter.CameraList[0].CameraName;
                version_tx.Text = "版本号：" + this.ProductVersion;
                rlabelOperID.Text = "从机" + Device.Parameter.CameraList[0].CameraName.Replace("相机", "");
                this.batchID.Text = string.Format("当前型号:{0}", Device.Parameter.DefaultProductId);
                actionMain0.Wait();
                this.Enabled = true;
                //IsDisImage.Checked = false;//是否显示过程图
                Device.IsDisImage = IsDisImage.Checked;
                refreshbox();
                this.Activate();
                timer1.Enabled = true;
                radPageView1.SelectedPage = PageStatus;
            }
            catch (Exception ex)
            {
                _log.Error("从机启动失败" + ex.ToString());
                MessageBox.Show(ex.Message);
                this.Enabled = true;
            }
        }

        private void ProgressValueChanged(int value)
        {
            if (value > ProgressBar.Maximum)
                return;
            InvokeIfNeeded(ProgressBar, () => ProgressBar.Value1 = value);
        }

        private void Intance_MsgEvent(string arg1, int index)
        {
            switch (index)
            {
                case 0:
                    Start(arg1);
                    break;
                case 1:
                    ChangeProductEvent(arg1);
                    break;
                case 2:
                    DisResult(arg1);
                    break;

            }
        }

        private void DisResult(string res)
        {
            _log.Debug("MainForm更新结果：" + res.ToString());
            Action changesys = () =>
            {
                if (res.Equals("True"))
                {
                    ChangeBackColor(radPanel_c0, Color.Green);
                    result_lable.Text += "OK";
                }
                else
                {
                    ChangeBackColor(radPanel_c0, Color.Red);
                    result_lable.Text += "NG";
                }
                if (listView1.Items.Count > 0)
                {
                    listView1.Items[0].Selected = true;
                }
                else
                {
                    imageRenderBox1.ClearRectBox();
                    imageRenderBox1.ClearImage();
                    imageRenderBox1.DisplayRefresh();
                }
                if (ImageManage.Instance.ConnectState)
                {
                    if (ProgressBar.Maximum > ProgressBar.Value1 && ProgressBar.Minimum <= ProgressBar.Value1)
                        ProgressBar.Value1 = ProgressBar.Maximum;
                }
                SysInfoTex.Text += "-已向主机发送结果";
            };
            InvokeIfNeeded(radStatusStrip1, changesys);
        }

        private void radMenuItem4_Click(object sender, EventArgs e)
        {
            try
            {
                Device.EnginerModel = false;
                LogInForm lf = new LogInForm();
                lf.ShowDialog();
                if (!Device.EnginerModel)
                    return;
                configForm cf = new configForm();
                cf.ShowDialog();
                cf.Dispose();
                Device.EnginerModel = false;
                this.batchID.Text = string.Format("当前型号:{0}", Device.Parameter.DefaultProductId);
                InspEntity.Intance.GetProjectConfig();
            }
            catch { }
        }

        private void menuUser_Click(object sender, EventArgs e)
        {
            UserForm user = new UserForm();
            if (user.ShowDialog() == DialogResult.OK)
            {
                rlabelOperID.Text = string.Format("操作员ID:{0}", Device.Parameter.CurentOperator);
            }
        }

        private void yieldAnaly_Click(object sender, EventArgs e)
        {
            YieldAnalyForm yf = new YieldAnalyForm();
            yf.Show();
        }

        private void DisMode_Click(object sender, EventArgs e)
        {
            DisMode.IsChecked = !DisMode.IsChecked;
            if (DisMode.IsChecked)
            {
                radSplitContainer1.SplitPanels[1].Collapsed = true;
                this.FormBorderStyle = FormBorderStyle.None;
                this.WindowState = FormWindowState.Maximized;
            }
            else
            {
                radSplitContainer1.SplitPanels[1].Collapsed = false;
                this.WindowState = FormWindowState.Normal;
                this.FormBorderStyle = FormBorderStyle.FixedDialog;
            }
        }

        private void ExitSys_btn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("即将退出检测系统？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                this.Close();
            }
        }

        private void showErrRegionCB_ToggleStateChanged(object sender, Telerik.WinControls.UI.StateChangedEventArgs args)
        {
            if (listView1.Items.Count <= 0)
                return;
            if (listView1.SelectedIndices.Count > 0)
            {
                var ind = listView1.SelectedIndices[0];
                ShowImag(Convert.ToInt32(listView1.Items[ind].Name), imageRenderBox1, ImageManage.Instance.Insprecord.ListResults, showErrRegionCB.Checked, showTestDataRCB.Checked);
            }
        }

        private void showTestDataRCB_ToggleStateChanged(object sender, Telerik.WinControls.UI.StateChangedEventArgs args)
        {
            if (listView1.Items.Count <= 0)
                return;
            if (listView1.SelectedIndices.Count > 0)
            {
                var ind = listView1.SelectedIndices[0];
                ShowImag(Convert.ToInt32(listView1.Items[ind].Name), imageRenderBox1, ImageManage.Instance.Insprecord.ListResults, showErrRegionCB.Checked, showTestDataRCB.Checked);
            }
        }

        private void autoAddIDRCB_ToggleStateChanged(object sender, Telerik.WinControls.UI.StateChangedEventArgs args)
        {
            Device.SaveSourceImage = autoAddIDRCB.Checked;
        }

        private void IsDisImage_ToggleStateChanged(object sender, Telerik.WinControls.UI.StateChangedEventArgs args)
        {
            Device.IsDisImage = IsDisImage.Checked;
        }
        private void HostDis_ToggleStateChanged(object sender, Telerik.WinControls.UI.StateChangedEventArgs args)
        {
            Device.IsHostDisPlay = HostDis.Checked;
        }
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedIndices.Count > 0 && ImageManage.Instance.Insprecord != null && ImageManage.Instance.Insprecord.ListResults != null && ImageManage.Instance.Insprecord.ListResults.Count > 0)
            {
                var ind = listView1.SelectedIndices[0];
                ShowImag(Convert.ToInt32(listView1.Items[ind].Name), imageRenderBox1, ImageManage.Instance.Insprecord.ListResults, showErrRegionCB.Checked, showTestDataRCB.Checked);
            }
        }

        private void setEXtimeRbtn_Click(object sender, EventArgs e)
        {
            if (ExpouseTimeRTB.Text.Trim() == "")
                return;
            ImageManage.Instance.SetExposureTime(Convert.ToInt32(ExpouseTimeRTB.Text.Trim()));
            Thread.Sleep(50);
        }

        private void sigleShotRBtn_Click(object sender, EventArgs e)
        {
            InspEntity.InspState = 99;
            ImageManage.Instance.OneShot();
            int s = 30;
            while (s > 0 && ImageManage.CatchedBMP == null)
            {
                s--;
                Thread.Sleep(100);
            }
            if (s > 0)
            {
                CamerConfig cc = new CamerConfig();
                cc.ShowDialog();
                cc.Dispose();
            }
            else
            {
                MessageBox.Show("拍照超时：3s");
            }
        }

        private void ContinueShot_RBtn_Click(object sender, EventArgs e)
        {
            try
            {
                fu = null;
                InspEntity.InspState = 99;
                ImageManage.Instance.ContinueShot();
                fu = new FormUser();
                fu.Show();
                fu.FormClosing += fp_FormClosing;
            }
            catch (Exception ex)
            { }
        }

        private void fp_FormClosing(object sender, FormClosingEventArgs e)
        {
            ImageManage.Instance.StopContinueShot();
        }

        private void continuShotRBtn_Click(object sender, EventArgs e)
        {
            #region 查看接收的指令
            try
            {
                if (ImageManage.Instance.CmdListStr.Count > 0)
                {
                    listBox1.Items.Clear();
                    foreach (var s in ImageManage.Instance.CmdListStr)
                    {
                        listBox1.Items.Add(s);
                    }
                    for (int i = 0; i < listView1.LargeImageList.Images.Count; i++)
                    {
                        Image img = listView1.LargeImageList.Images[i];
                        img.Dispose();
                        img = null;
                    }
                    listView1.LargeImageList.Images.Clear();
                    listView1.Items.Clear();
                }
                lock (ImageManage.Instance.Insprecord.ListResults)
                {
                    ImageManage.Instance.Insprecord.ListResults.ForEach(x => c00_RefrushListView(x as ResultDisplayRowResult));
                }
            }
            catch (Exception ex)
            {

            }
            #endregion
        }

        private void CorrectRBtn_Click(object sender, EventArgs e)
        {
            InspEntity.InspState = 0;
            correct();
        }

        private void DustUpRBtn_Click(object sender, EventArgs e)
        {
            try
            {
                var name = (sender as RadButton).Name.ToLower();
                if (name.Contains("rbtn"))//读清灰图
                {
                    var index = name.Contains("up") ? -3 : -2;
                    var temp = Device.defaultProduct.ParamList.Find(x => x.PicParameter.Picindex == index);
                    if (temp == null)
                        MessageBox.Show("该型号未配置清灰" + index);
                    var bmp = GetPic();
                    if (bmp != null)
                    {
                        ImageManage.Instance.ReceiveCmd(100, index);
                        ImageManage.Instance.ImageProcess(null,bmp);
                    }
                }
                else if (name.Contains("pbtn"))//处理清灰图
                {
                    var index = name.Contains("up") ? 0 : 1;
                    var res = ImageManage.Instance.InspDust(index);
                    MessageBox.Show(string.Format("清灰{0}", (res == 1).ToString()));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("" + ex.ToString());
            }
        }

        private Bitmap GetPic()
        {
            OpenFileDialog op = new OpenFileDialog();
            Bitmap m_bmp = null;
            if (op.ShowDialog() == DialogResult.OK)
            {
                ImageManage.Instance.ReadLocal = true;
                m_bmp = new Bitmap(op.FileName);
            }
            return m_bmp;
        }

        private void ManInsp_Btn_Click(object sender, EventArgs e)
        {
            try
            {
                btlist.ToList().ForEach(x =>
                {
                    if (x != null) x.Dispose();
                });
                if (InspEntity.InspState == -1 && MessageBox.Show("输入两张清灰图", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    for (int i = 0; i < 2; i++)
                    {
                        OpenFileDialog op = new OpenFileDialog();
                        if (op.ShowDialog() == DialogResult.OK)
                        {
                            btlist[i] = new Bitmap(op.FileName);
                        }
                        else
                        {
                            MessageBox.Show("已取消");
                            return;
                        }
                    }
                    MessageBox.Show("清灰图已输入，请输入目测图", "提示", MessageBoxButtons.OKCancel);
                }
                OpenFileDialog opp = new OpenFileDialog();
                Bitmap m_bmp;
                if (opp.ShowDialog() == DialogResult.OK)
                {
                    m_bmp = new Bitmap(opp.FileName);
                    if (InspEntity.InspState == -1)
                    {
                        btlist[2] = m_bmp;
                        ImageManage.Instance.ProcessInspMap(new InspImageInfo(new Bitmap[] { btlist[2], btlist[0], btlist[1] }, InspEntity.InspState, true));
                    }
                    else
                        ImageManage.Instance.ProcessInspMap(new InspImageInfo(new Bitmap[] { (Bitmap)m_bmp.Clone() }, InspEntity.InspState, true));
                    var item = ImageManage.Instance.Insprecord.ListResults.Select(x =>
                    {
                        var t = x as ResultDisplayRowResult;
                        if (t.Index.Equals(InspEntity.InspState))
                            return t.InspedImg;
                        else
                            return null;
                    });
                    if (item == null || item.Last() == null) return;
                    imageRenderBox1.DisplayImage(item.Last());
                    imageRenderBox1.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("" + ex.Message + ex.TargetSite);
            }
        }

        private void ShotInsp_Btn_Click(object sender, EventArgs e)
        {
            int index = InspEntity.InspState;
            if (index == -1 && ImageManage.Instance.dustPicList.Count != 2)
            {
                MessageBox.Show("清灰图数量不足，请重新拍上下清灰");
                return;
            }
            var temp = Device.defaultProduct.ParamList.Where(x => x.PicParameter.Picindex.Equals(index)).Select(x => x.PicParameter.ExproseTime);
            if (temp == null || temp.ToList().Count < 1)
                return;
            tempexprosetime = temp.First();
            ImageManage.Instance.ReceiveCmd(tempexprosetime, index);
        }

        private void RefreshRBtn_Click(object sender, EventArgs e)
        {
            Device.defaultProduct = ProductManager.OpenProduct(Device.Parameter.DefaultProductId);
            ImageManage.Instance.Refrush(1);
            refreshbox();
            #region 控件清空
            Action actionRestart = () =>
            {
                ChangeBackColor(radPanel_c0, Color.CornflowerBlue);
                ProgressBar.Value1 = 0;
                ProgressBar.Value2 = 0;
                result_lable.Text = "API检测结果:";
                imageRenderBox1.ClearRectBox();
                imageRenderBox1.ClearImage();
                imageRenderBox1.DisplayRefresh();
                for (int i = 0; i < listView1.LargeImageList.Images.Count; i++)
                {
                    Image img = listView1.LargeImageList.Images[i];
                    img.Dispose();
                    img = null;
                }
                listView1.LargeImageList.Images.Clear();
                listView1.Items.Clear();
                SysInfoTex.Text = "系统消息：";
                SysInfoTex.BackColor = Color.LightGray;
            };
            InvokeIfNeeded(this, actionRestart);
            #endregion 控件清空
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Device.SaveParameter();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (var s in btlist)
            {
                if (s != null)
                    s.Dispose();
            }
            btlist = new Bitmap[3];
            if (comboBox1.SelectedIndex < 0)
                return;
            var picinfo = Device.defaultProduct.ParamList.Find(x => x.PicParameter.Picname.Equals(comboBox1.Text));
            if (picinfo == null)
                return;
            InspEntity.InspState = picinfo.PicParameter.Picindex;
        }
        private void c00_RefrushListView(ResultDisplayRowResult curentErrInfo)
        {
            CutErrRegion(curentErrInfo, listView1);
        }

        private void c00_RefrushContinueCapturePic(Bitmap bit)
        {
            if (fu != null && !fu.IsDisposed)
                fu.m_bitmap = bit;
        }
        /// <summary>
        /// 应用程序初始化
        /// </summary>
        private void InitApplication()
        {
            Device.AppPath = Application.StartupPath;//获取应用程序所在路径
            Device.ProjectPath = Path.Combine(Device.AppPath, "Projects");//创建项目存放路径
            if (!Directory.Exists(Device.ProjectPath))
            {
                Directory.CreateDirectory(Device.ProjectPath);
            }
            Device.LogPath = Path.Combine(Device.AppPath, "Log");  //创建日志存放路径
            if (!Directory.Exists(Device.LogPath))
            {
                Directory.CreateDirectory(Device.LogPath);
            }
            Device.ExtraPathDir = Path.Combine(Device.AppPath, "SourceImage");
            if (!Directory.Exists(Device.ExtraPathDir))
            {
                Directory.CreateDirectory(Device.ExtraPathDir);
            }

        }

        #region 获取项目配置信息（已更改）

        private void refreshbox()
        {
            comboBox1.Items.Clear();
            Device.defaultProduct.ParamList.ForEach(x => comboBox1.Items.Add(x.PicParameter.Picname));
            comboBox1.Text = "";
            comboBox1.Refresh();
        }
        #endregion 获取项目配置信息（已更改）

        #region 检测
        /// <summary>
        /// 执行检测，所有相机都再此进行检测，每个相机单独检测
        /// </summary>
        private bool GetResult(string AisId)
        {
            if (MainInspEnable)//如果检测中
            {
                _log.Warn("MainForm=>" + "检测过程未结束，退回检测任务！");
                Msg = "检测未完成：已退回检测任务！";
                return false;
            }
            try
            {
                MainInspEnable = true;
                _log.Debug("MainForm=>" + "进入检测主线程");

                var result = QueryResult();

                MainInspEnable = false;//检测结束
                _log.Debug("MainForm=>" + "界面更新完成，本次检测完成" + result.ToString());
                return result;
            }
            catch (Exception ex)
            {
                _log.Error("MainForm=>" + "检测过程出错" + ex.ToString());
                MainInspEnable = false;//检测结束
                SysInfoTex.Text = "API检测异常:" + ex.Message;
                return false;
            }
        }
        #endregion 检测（主业务逻辑处理）

        #region 公用方法

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ctl"></param>
        /// <param name="doit"></param>
        private void InvokeIfNeeded<T>(T ctl, Action doit) where T : Control
        {
            if (ctl.InvokeRequired)
            {
                ctl.BeginInvoke(doit);
            }
            else
            {
                doit();
            }
        }

        private string GetCustomizedDateTimeString(DateTime d)
        {
            var f = string.Format("{0}-{1}-{2}/{3}:{4}:{5}", d.Year, d.Month.ToString("d2"), d.Day.ToString("d2"), d.Hour, d.Minute, d.Second);
            return f;
        }

        private void ChangeBackColor<T>(T ctrl, Color color) where T : RadControl
        {
            try
            {
                ((Telerik.WinControls.Primitives.FillPrimitive)(ctrl.GetChildAt(0).GetChildAt(0))).BackColor = color;
                ((Telerik.WinControls.Primitives.FillPrimitive)(ctrl.GetChildAt(0).GetChildAt(0))).BackColor2 = color;
                ((Telerik.WinControls.Primitives.FillPrimitive)(ctrl.GetChildAt(0).GetChildAt(0))).BackColor3 = color;
                ((Telerik.WinControls.Primitives.FillPrimitive)(ctrl.GetChildAt(0).GetChildAt(0))).BackColor4 = color;
            }
            catch (Exception ex) { }
        }
        #endregion

        public void CutErrRegion(ResultDisplayRowResult curentErrInfo, ListView lv)
        {
            List<int> C = curentErrInfo.ErrCol;
            List<int> R = curentErrInfo.ErrRow;
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(85, 85);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            if (C != null && C.Count != 0)
            {
                int jcount = 0;
                Bitmap bbm = (Bitmap)curentErrInfo.InspedImg.Clone();
                int sxCount = C.Count - jcount;
                if (sxCount <= 4)
                {
                    for (int i = 0; i < sxCount; i++)
                    {
                        int colc = (int)C[i + jcount];
                        int rowc = (int)R[i + jcount];

                        if (sxCount == 1)//1个的方案
                        {
                            g.DrawImage(bbm, new Rectangle(17, 17, 50, 50), (int)colc - 20, (int)rowc - 20, 40, 40, GraphicsUnit.Pixel);
                        }
                        else if (sxCount == 2)//2个的方案
                        {
                            g.DrawImage(bbm, new Rectangle(i % 2 == 0 ? 0 : 45, 20, 40, 40), (int)colc - 20, (int)rowc - 20, 40, 40, GraphicsUnit.Pixel);
                        }
                        else //3和4
                        {
                            g.DrawImage(bbm, new Rectangle(i % 2 == 0 ? 0 : 45, (i / 2) * 45, 40, 40), (int)colc - 20, (int)rowc - 20, 40, 40, GraphicsUnit.Pixel);
                        }

                    }

                }
                else//大于4
                {
                    for (int i = 0; i < 4; i++)
                    {
                        int colc = (int)C[i + jcount];
                        int rowc = (int)R[i + jcount];

                        g.DrawImage(bbm, new Rectangle(i % 2 == 0 ? 0 : 45, (i / 2) * 45, 40, 40), (int)colc - 20, (int)rowc - 20, 40, 40, GraphicsUnit.Pixel);
                    }

                }
                //Application.DoEvents();
                Action actionNGAdd = () =>
                {
                    lv.LargeImageList.Images.Add(bitmap);

                    if (C.Count > 4)//jcount == 4 && 
                    {
                        lv.Items.Add(curentErrInfo.Index.ToString(), string.Format("{0}-{1}", curentErrInfo.ItemName, curentErrInfo.Msg), lv.LargeImageList.Images.Count - 1);
                        lv.Items[lv.Items.Count - 1].ForeColor = Color.Gold;// Color.SpringGreen
                    }
                    else
                    {
                        lv.Items.Add(curentErrInfo.Index.ToString(), string.Format("{0}-{1}", curentErrInfo.ItemName, curentErrInfo.Msg), lv.LargeImageList.Images.Count - 1);
                        if (!curentErrInfo.Result)
                        {
                            lv.Items[lv.Items.Count - 1].ForeColor = Color.Red;// Color.SpringGreen
                        }
                        else
                            lv.Items[lv.Items.Count - 1].ForeColor = Color.Green;// Color.SpringGreen
                    }

                };
                InvokeIfNeeded(lv, actionNGAdd);
                g.Dispose();
                //bitmap.Dispose();
                //bitmap = null;
                bbm.Dispose();
                bbm = null;
            }
            else
            {
                if (curentErrInfo.Result)
                {
                    Action actionOKAdd = () =>
                    {
                        lv.LargeImageList.Images.Add(bitmap);
                        lv.Items.Add(curentErrInfo.Index.ToString(), string.Format("{0}-{1}", curentErrInfo.ItemName, curentErrInfo.Msg), lv.LargeImageList.Images.Count - 1);
                        lv.Items[lv.Items.Count - 1].ForeColor = Color.Green;// Color.SpringGreen

                    };
                    InvokeIfNeeded(lv, actionOKAdd);
                }
                else
                {
                    Action actionNNGAdd = () =>
                    {
                        lv.LargeImageList.Images.Add(bitmap);
                        lv.Items.Add(curentErrInfo.Index.ToString(), string.Format("{0}-{1}", curentErrInfo.ItemName, curentErrInfo.Msg), lv.LargeImageList.Images.Count - 1);
                        lv.Items[lv.Items.Count - 1].ForeColor = Color.Red;// Color.SpringGreen

                    };
                    InvokeIfNeeded(lv, actionNNGAdd);
                }
                g.Dispose();
            }


        }
        /// <summary>
        /// show image to imagebox
        /// </summary>
        /// <param name="ind"></param>
        public void ShowImag(int ind, ImageRender.ImageRenderBox irb, List<BaseDisplayRowResult> rlist, bool showERegion, bool ShowData)
        {
            Bitmap bbm = null;
            try
            {
                var sel = rlist.Find(item => (item as ResultDisplayRowResult).Index == ind);
                if (sel == null)
                    return;
                ResultDisplayRowResult ar = sel as ResultDisplayRowResult;
                bbm = (Bitmap)ar.InspedImg.Clone();
                int w = bbm.Width, h = bbm.Height;
                if (showERegion && !ShowData)
                {
                    var tempCol = ar.ErrCol;
                    var tempRow = ar.ErrRow;
                    irb.ClearRectBox();
                    irb.ClearString();
                    for (int i = 0; i < tempCol.Count; i++)
                        irb.AddRectBox(80, 4, tempCol[i], tempRow[i]);
                    irb.DisplayImage(bbm);
                    irb.DisplayRefresh();
                }
                else if (showERegion && ShowData)
                {
                    var tempCol = ar.ErrCol;
                    var tempRow = ar.ErrRow;
                    var tempValue = ar.ErrValue;
                    var tempType = ar.ErrType;
                    var tempDiff = ar.ErrDiff;
                    irb.ClearRectBox();
                    irb.ClearString();
                    if (tempDiff != null)
                        for (int i = 0; i < tempCol.Count; i++)
                        {
                            irb.AddRectBox(80, 4, tempCol[i], tempRow[i]);
                            irb.AddString(8, string.Format("{0},{1},{2}", tempType[i], tempValue[i], tempDiff[i]), tempCol[i], tempRow[i], 0, 0, 255);
                        }
                    else
                        for (int i = 0; i < tempCol.Count; i++)
                        {
                            irb.AddRectBox(80, 4, tempCol[i], tempRow[i]);
                            irb.AddString(8, string.Format("{0},{1}", tempType[i], tempValue[i]), tempCol[i], tempRow[i], 0, 0, 255);
                        }
                    irb.DisplayImage(bbm);
                    irb.DisplayRefresh();
                }
                else if (!showERegion && ShowData)
                {
                    var tempCol = ar.ErrCol;
                    var tempRow = ar.ErrRow;
                    var tempValue = ar.ErrValue;
                    var tempType = ar.ErrType;
                    var tempDiff = ar.ErrDiff;
                    irb.ClearRectBox();
                    irb.ClearString();
                    if (tempDiff != null)
                        for (int i = 0; i < tempCol.Count; i++)
                        {
                            irb.AddRectBox(80, 4, tempCol[i], tempRow[i]);
                        }
                    else
                        for (int i = 0; i < tempCol.Count; i++)
                        {
                            irb.AddRectBox(80, 4, tempCol[i], tempRow[i]);
                        }
                    irb.DisplayImage(bbm);
                    irb.DisplayRefresh();
                }
                else
                {
                    irb.ClearRectBox();
                    irb.ClearString();
                    irb.DisplayImage(bbm);
                    irb.DisplayRefresh();
                }
                bbm.Dispose();
                bbm = null;
            }
            catch (Exception ex)
            {

                if (bbm != null)
                {
                    bbm.Dispose();
                    bbm = null;
                }
                //MessageBox.Show(ex.Message);
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Shift | Keys.ShiftKey:
                    break;
                case Keys.RButton | Keys.ShiftKey | Keys.Alt:
                    showErrRegionCB.Focus();
                    if (showErrRegionCB.Checked)
                    {
                        showErrRegionCB.Checked = false;
                    }
                    else
                    { showErrRegionCB.Checked = true; }
                    break;
                case Keys.Down:
                case Keys.Up:
                case Keys.Left:
                case Keys.Right:
                    listView1.Focus();
                    if (listView1.Items.Count > 0 && !listView1.Focused)
                        listView1.Items[0].Selected = true;
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        FormPic fp = null;
        FormUser fu = null;

        //开始并清理缓存
        internal void Start(string id)
        {
            try
            {
                #region 控件清空
                Action actionRestart = () =>
                {
                    IdText.Text = id;
                    ChangeBackColor(radPanel_c0, Color.CornflowerBlue);
                    ProgressBar.Value1 = 0;
                    ProgressBar.Value2 = 0;
                    ProgressBar.Maximum = InspEntity.Intance.InspLogic.GetNeeds();
                    ProgressBar.Refresh();
                    result_lable.Text = "API检测结果:";
                    imageRenderBox1.ClearRectBox();
                    imageRenderBox1.ClearImage();
                    imageRenderBox1.DisplayRefresh();
                    for (var i = 0; i < listView1.LargeImageList.Images.Count; i++)
                    {
                        var img = listView1.LargeImageList.Images[i];
                        img.Dispose();
                        img = null;
                    }
                    listView1.LargeImageList.Images.Clear();
                    listView1.Items.Clear();
                    SysInfoTex.Text = "系统消息：";
                    SysInfoTex.BackColor = Color.LightGray;
                    listBox1.Items.Clear();
                };
                InvokeIfNeeded(this, actionRestart);
                #endregion 控件清空
                _log.Debug("\r\nMainForm=>" + "检测开始");
            }
            catch (Exception ex)
            {
                _log.Error("FormMain.Start()异常：" + ex.Message);
            }
        }
        internal void ChangeProductEvent(string msg)
        {
            try
            {
                InvokeIfNeeded(this, new Action(() =>
                {
                    this.batchID.Text = string.Format("当前型号:{0}", Device.Parameter.DefaultProductId);
                    commandBarSeparator1.Text = msg;
                    PageOffline.Enabled = false;
                }));
            }
            catch
            {
            }
        }


        public delegate void BackResultEventHandler(bool bl, string subid);
        public event BackResultEventHandler OnBackResult = null;//利用WinForm的EventHandler，如不采用则必须自定义委托和事件

        internal void HandleLight(int ind, int inten)
        {
            try
            {
                //switch (ind)
                //{
                //    case 0:
                //        Device.Slup.Sendcmd(inten == 0 ? CmdItem.close : CmdItem.open, (byte) inten);
                //        break;
                //    case 1:
                //        Device.Sldown.Sendcmd(inten == 0 ? CmdItem.close : CmdItem.open, (byte) inten);
                //        break;
                //    case 2:
                //        Device.Bl.SetConstInt(1, (byte) inten);
                //        break;
                //    default:
                //        break;
                //}
            }
            catch
            {
            }
        }
        internal bool QueryResult()
        {
            DateTime dtStart = DateTime.Now;
            bool blnPass = false;
            bool isabort = false;
            int count = InspEntity.Intance.InspLogic.GetNeeds() + 1;//加定位、校正
            int times = Device.defaultProduct.Delaytime.AllResults;//等待两分钟
            var errtype = 0;
            var start = DateTime.Now;
            Msg = "检测进行中";
            while (times-- > 0)
            {
                if (ImageManage.Instance.ResultAll.Result)
                    break;
                Thread.Sleep(10);
            }
            //return timeout < 1;
            var list = ImageManage.Instance.Insprecord.ListResults;
            var f1 = ImageManage.Instance.ResultAll.ErrCol.Count > 0;
            var f2 = list.Count == count;
            var f3 = times > 0;
            var f4 = ImageManage.Instance.CorrectRlt.GetHashCode() == (ItemResult.pass).GetHashCode();
            if (!f1 && f2 && f4)
            {
                ImageManage.Instance.Insprecord.InspResult = 1;
                blnPass = true;
                _log.Trace("检测结束：OK");
                Msg = "检测结束：OK";
            }
            else
            {
                blnPass = false;
                string str = "";
                if (isabort)
                    str = string.Format("检测结束：NG，原因为：{0}|{1}|中止检测", f4 ? "" : "校正", (!f1) ? "" : "检测");
                else
                    str = string.Format("检测结束：NG，原因为：{0}|{1}|{2}|{3}", f4 ? "" : "校正", (!f1) ? "" : "检测", f2 ? "" : "项数", f3 ? "" : "超时");
                _log.Trace(str);
                Msg = str;
                var temp = ImageManage.Instance.Insprecord.ListResults;
                if (errtype == 0 && temp.Count > 0)
                {
                    if (temp.Any(x => ((ResultDisplayRowResult)x).ErrType.Count > 0))
                    {
                        var tfirst = temp.First(x => ((ResultDisplayRowResult)x).ErrType.Count > 0);
                        errtype = (tfirst as ResultDisplayRowResult).ErrType.First();
                    }
                }
                ImageManage.Instance.Insprecord.ErrCode = NGSort.TypeSort(errtype);
            }

            #region 回传结果信息
            if (OnBackResult != null && Device.ICEconnection)
            {
                OnBackResult(blnPass, Device.SubID);//回传的数据，怎样获取传过来的数据
                _log.Debug("MainForm=>" + "已向主机发送结果" + blnPass.ToString());
                Action changesys = () =>
                {
                    SysInfoTex.Text += "-已向主机发送结果";
                };
                InvokeIfNeeded(radStatusStrip1, changesys);
            }
            #endregion

            #region 保存检测记录
            Task.Run(() =>
            {
                var endtime = DateTime.Now;
                ImageManage.Instance.Insprecord.StartTime = start.ToString("yyyyMMddHHmmssffff");
                ImageManage.Instance.Insprecord.Duaration = Convert.ToInt32((endtime - start).TotalSeconds);
                ImageManage.Instance.Insprecord.EndTime = endtime.ToString("yyyyMMddHHmmssffff");
                (new ExcelHandle()).SaveRecord(ImageManage.Instance.Insprecord, ImageManage.Instance.Cameraname);
                _log.Debug("MainForm=>" + "保存结果完成");//检测结果保存
            });
            #endregion 保存检测记录

            #region 改变结果显示
            Action actionChangeRelut0 = () =>
            {
                if (blnPass)
                {
                    ChangeBackColor(radPanel_c0, Color.Green);
                    result_lable.Text += "OK";
                }
                else
                {
                    ChangeBackColor(radPanel_c0, Color.Red);
                    result_lable.Text += "NG";
                }
                if (listView1.Items.Count > 0)
                {
                    listView1.Items[0].Selected = true;
                }
                else
                {
                    imageRenderBox1.ClearRectBox();
                    imageRenderBox1.ClearImage();
                    imageRenderBox1.DisplayRefresh();
                }
                if (ImageManage.Instance.ConnectState)
                {
                    if (ProgressBar.Maximum > ProgressBar.Value1 && ProgressBar.Minimum <= ProgressBar.Value1)
                        ProgressBar.Value1++;
                }
            };
            InvokeIfNeeded(this, actionChangeRelut0);
            Action actProg = () =>
            {
                ProgressBar.Value1 = ProgressBar.Maximum;
            };
            InvokeIfNeeded(ProgressBar, actProg);
            #endregion 改变结果显示

            return blnPass;
        }
        void correct()
        {
            try
            {
                OpenFileDialog op = new OpenFileDialog();
                Bitmap m_bmp;
                if (op.ShowDialog() == DialogResult.OK)
                {
                    m_bmp = new Bitmap(op.FileName);
                    if (ImageManage.Instance.Insprecord.ListResults != null)//AisRecord.ListResults != null
                    {
                        for (int i = 0; i < ImageManage.Instance.Insprecord.ListResults.Count; i++)
                        {
                            var t = ImageManage.Instance.Insprecord.ListResults[i] as ResultDisplayRowResult;
                            if (t.ErrCol != null)
                                t.ErrCol.Clear();
                            if (t.ErrRow != null)
                                t.ErrRow.Clear();
                            if (t.ErrType != null)
                                t.ErrType.Clear();
                            if (t.ErrValue != null)
                                t.ErrValue.Clear();
                            if (t.InspedImg != null)
                            {
                                t.InspedImg.Dispose();
                                t.InspedImg = null;
                            }
                            GC.Collect();
                        }
                        ImageManage.Instance.Insprecord.ListResults.Clear();
                    }
                    else
                    {
                        ImageManage.Instance.Insprecord.ListResults = new List<BaseDisplayRowResult>();
                    }
                    var res = ImageManage.Instance.InspCorrect(m_bmp);
                    MessageBox.Show(string.Format("校正{0}", res ? "成功" : "失败"));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("校正失败" + ex.Message + ex.TargetSite);
            }
        }

        private void SinglefolderExcute_Btn_Click(object sender, EventArgs e)
        {
            try
            {
                var times = 0;
                if (!int.TryParse(timesTBox.Text, out times))
                    return;
                if (!repeatBox.Checked)
                    times = 0;
                var count = times + 1;
                var dialog = new FolderBrowserDialog();
                if (dialog.ShowDialog() != DialogResult.OK) return;
                var path = dialog.SelectedPath;
                ImageManage.Instance.ChangeVirtualCamera(path);
                _resetEvent.Reset();
                _resetEvent.Set();
                for (var i = 0; i < times + 1; i++)
                {
                    var task = Task.Factory.StartNew(() =>
                    {
                        _resetEvent.WaitOne();
                        InspEntity.Intance.ExcuteCmd();
                    });
                    task.ContinueWith(x =>
                   {
                       while (!ImageManage.Instance.ResultAll.Result)
                       {
                           Thread.Sleep(10);
                       }
                       InvokeIfNeeded(this, new Action(() =>
                       {
                           timesTBox.Text = (--count).ToString();
                       }));
                       _resetEvent.Set();
                       if (count <= 1)
                           ImageManage.Instance.VirtualCameraDisable();
                   });
                }
            }
            catch (Exception ex)
            {
                ImageManage.Instance.ReadLocal = false;
                MessageBox.Show("Error" + ex.Message);
            }
        }

        private void Processfolder(string path)
        {

        }

        private List<string> GetDirectories(string path)
        {
            if (Directory.Exists(path))
            {
                string[] productList = Directory.GetDirectories(path);
                return productList.ToList();
            }
            else
                return null;
        }
        private void radTrackBar1_ValueChanged(object sender, EventArgs e)
        {
            Sleeptime.Text = radTrackBar1.Value.ToString();
        }

        private void radTrackBar2_ValueChanged(object sender, EventArgs e)
        {
            Sleeptime2.Text = radTrackBar2.Value.ToString();
        }

        private void MultilefolderExcute_Btn_Click(object sender, EventArgs e)
        {
            try
            {
                var sleeptime = int.Parse(Sleeptime2.Text);
                var dialog = new FolderBrowserDialog();
                if (dialog.ShowDialog() != DialogResult.OK) return;
                var path = dialog.SelectedPath;
                radLabel3.Text = path;
                var pathllist = GetDirectories(path);
                for (var i = 0; i < pathllist.Count; i++)
                {
                    var timeout = _retset.WaitOne(10000);
                    MessageBox.Show(timeout ? "未超时" : "超时：10000ms");
                    Processfolder(pathllist[i]);
                    Thread.Sleep(int.Parse(Sleeptime2.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("MutlifolderError" + ex.ToString());
            }
        }

        private void repeatBox_CheckedChanged(object sender, EventArgs e)
        {
            repeatBox.BackColor = repeatBox.Checked ? Color.Chartreuse : Color.DarkGray;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            InvokeIfNeeded(this, () =>
            {
                SysInfoTex.Text = InspEntity.Msg;
                runmodetex.Text = Device.Automode ? "自动模式" : "调试模式";
            });
        }

        private void ManualInspBtn_Click(object sender, EventArgs e)
        {
            InspEntity.Intance.ExcuteCmd();
        }
    }
}
